import { Controller, Get, Query, Sse } from '@nestjs/common';
import { DeviceService } from './device.service';
import { DaemonService } from '../daemon/daemon.service';
import { WifiIpService } from '../wifi-ip/wifi-ip.service';
import { Device } from './entity/device.entity';
import { DeviceListService } from './list.service';
import { Observable } from 'rxjs';

interface IGetDeviceQuery {
  SN: string;
  isListInfo: string;
}

@Controller()
export class DeviceController {
  constructor(
    private readonly deviceService: DeviceService,
    private readonly deviceListService: DeviceListService,
    private readonly daemonService: DaemonService,
    private readonly wifiIpService: WifiIpService,
  ) {}

  @Get('/device-info')
  async getDevice(@Query() query: IGetDeviceQuery): Promise<Device> {
    const isListInfo = query.isListInfo === 'true';
    const info = await this.deviceService.getDeviceInfo(query.SN, isListInfo);
    info.wlan_ip = await this.wifiIpService.getWifiIP(query.SN, true);
    const is_hisi_gpu = info?.device_name?.includes?.('Mate 60 Pro');
    !isListInfo && this.daemonService.startDaemon(query.SN, is_hisi_gpu);
    return info;
  }

  @Sse('/device-list')
  getDeviceList(): Observable<MessageEvent> {
    return this.deviceListService.getDeviceList();
  }
}
